package com.github.chirspan.xaas.auth.web.api;

import com.github.chirspan.xaas.security.component.PermissionService;
import com.github.chirspan.xaas.core.rest.RestResult;
import com.github.chirspan.xaas.core.rest.RestResultStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * *******description*******
 * <p>
 * *************************
 *
 * @author chenpan
 * @date 2020/5/26 10:28
 */
@RestController
public class TokenController {

    @Autowired
    @Qualifier("tokenServices")
    DefaultTokenServices tokenServices;

    @Autowired
    JwtAccessTokenConverter accessTokenConverter;

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/oauth/check_token")
    RestResult checkToken(@RequestParam("token") String token) {
        try {
            OAuth2AccessToken accessToken = this.tokenServices.readAccessToken(token);
            if (accessToken == null) {
                return new RestResult(RestResultStatus.INVALID_TOKEN);
            } else if (accessToken.isExpired()) {
                return new RestResult(RestResultStatus.EXPIRED_TOKEN);
            } else {
                OAuth2Authentication authentication = this.tokenServices.loadAuthentication(token);
                return RestResult.OK(this.accessTokenConverter.convertAccessToken(accessToken, authentication), null);
            }
        } catch (InvalidTokenException e) {
            return new RestResult(RestResultStatus.CHECK_TOKEN_ERROR, e.getMessage(), null);
        }
    }

    @GetMapping("/oauth/check_permission")
    Boolean checkPermission(@RequestParam("token") String token,
                            @RequestParam(name = "requestUri") String requestUri,
                            @RequestParam(name = "requestMethod") String requestMethod) {
        try {
            OAuth2Authentication authentication = tokenServices.loadAuthentication(token);
            return permissionService.hasPermission(authentication, requestUri, requestMethod);
        } catch (Exception e) {
            return false;
        }
    }
}
